package com.my.blog.website.service.impl;

import cn.hutool.core.util.StrUtil;
import com.my.blog.website.config.QiniuUploadConfig;
import com.my.blog.website.service.UploadService;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * 描述...
 *
 * @author: Lee
 * @date: 2019/12/15
 */
@Service("uploadService")
public class UploadServiceImpl implements UploadService {
    @Autowired
    private QiniuUploadConfig config;

    @Override
    public Response upload(MultipartFile multipartFile) throws QiniuException, IOException {
        InputStream inputStream = multipartFile.getInputStream();
        Response response = config.uploadManager().put(inputStream, null, config.upToken(), null, null);
        return response;
    }

    @Override
    public Response upload(MultipartFile multipartFile, String key) throws IOException {
        InputStream inputStream = multipartFile.getInputStream();
        key = StrUtil.emptyToNull(key);
        return config.uploadManager().put(inputStream, key, config.upToken(), null, null);
    }

    @Override
    public String downloadUrl(String name) {
        // 文件名进行 urlencode 以兼容不同的字符
        String finalUrl = String.format("%s/%s", config.getDomain(), name);
        return finalUrl;
    }

    @Override
    public void delete(String name) throws QiniuException {
        config.bucketManager().delete(config.getBucket(), name);
    }
}
